package com.video.moderation.handler;

import com.alibaba.fastjson2.JSONObject;
import com.video.moderation.constant.SecurityConstants;
import com.video.moderation.entity.dto.Result;
import com.video.moderation.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    
    @Resource
    private JwtUtils jwtUtils;
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        
        String token = jwtUtils.generateJwtToken((Integer) authentication.getDetails(),authentication.getName());
        response.setHeader(SecurityConstants.AUTHORIZATION, token);
        Result res = Result.success("登录成功");

        ServletOutputStream outputStream = response.getOutputStream();

        outputStream.write(JSONObject.toJSONString(res).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
